<?php
namespace app\shop\controller\goods\ozon;

use app\common\model\shop\ozon\OzonGoodsModel;
use app\common\model\shop\ozon\OzonGoodsSkuModel;
use app\common\model\shop\ozon\OzonGoodsSkuStockModel;
use app\common\model\shop\ozon\OzonWarehouseModel;
use app\common\model\shop\PlatformModel;
use app\common\model\shop\ShopsModel;
use app\common\service\shop\Ozon;
use think\admin\Controller;
use think\admin\helper\QueryHelper;

/**
 * 库存管理
 * @Description
 * @class Inventory
 * @package app\shop\controller\goods\ozon
 * @author wangqinghui
 * @date 2024-12-30 10:37
 */
Class Inventory extends Controller
{
    /**
     * 库存列表
     * @Description
     * @auth true
     * @menu true
     * @author wangqinghui
     * @date 2024-12-30 10:40
     * @return void
     */
    public function index()
    {
        OzonGoodsSkuStockModel::mQuery()->layTable(function () {
            $this->title = lang('库存管理');
            // 推送状态组合
            $this->statusArr = OzonGoodsSkuStockModel::getPushStatusArr();
            // 仓库列表
            $map = [
                ['status', '=', 'created'],
            ];
            if(empty($this->super)){
                $map[] = ['account_id', '=', $this->account_id];
            }
            $this->warehouseList = OzonWarehouseModel::mk()->where($map)->column('warehouse_id,name');
            // 获取ozon平台
            $map = [
                ['status', '=', 1],
                ['code',    '=', 'ozon']
            ];
            $platform_id = PlatformModel::mk()->where($map)->value('id');
            // 店铺列表
            $map = [
                ['status', '=', 1],
                ['platform_id', '=', $platform_id]
            ];
            if(empty($this->super)){
                $map[] = ['account_id', '=', $this->account_id];
            }
            $this->shop_list = ShopsModel::mk()->where($map)->column('id,name');
        }, function (QueryHelper $query){
            $this->check_account = false;
            $this->check_user = false;
            $query->field('ogss.*,spo.spu_code,spo.title as spu_title');
            $query->alias('ogss')->join('shop_goods_ozon spo', 'ogss.goods_id=spo.id', 'left');
            $query->with(['warehouse', 'account', 'shop']);
            $query->equal('ogss.warehouse_id#warehouse_id,ogss.shop_id#shop_id,ogss.account_id#account_id,ogss.push_status#push_status,spo.spu_code#spu_code');
            $query->like('spo.title#spu_title');
            $query->order('ogss.id', 'desc');
        });
    }

    protected function _index_page_filter(array &$data)
    {
        $statusArr = OzonGoodsSkuStockModel::getPushStatusArr();
        foreach ($data as $key => $value) {
            $data[$key]['push_status_name'] = $statusArr[$value['push_status']];
        }
    }

    /**
     * 推送库存
     * @auth true
     * @Description
     * @author wangqinghui
     * @date 2024-12-31 11:30
     * @return void
     */
    public function pullStock()
    {
        $goods_nus = $this->request->post('goods_nus', '');
        if(empty($goods_nus)){
            $this->error('请选择需要同步的sku');
        }
        $gooods_nu_arr = explode(',', $goods_nus);
        if(empty($gooods_nu_arr)){
            $this->error('请选择需要同步的sku');
        }
        // 获取ozonsku信息
        $map = [
            ['goods_nu',    'in',   $gooods_nu_arr]
        ];
        $field = 'goods_nu,product_id,ozon_sku,goods_id';
        $sku_list = OzonGoodsSkuModel::mk()->field($field)->where($map)->select()->toArray();
        if(empty($sku_list)){
            $this->error('选择的sku信息有误');
        }
        // 获取商品信息
        $goods_id_arr = array_column($sku_list, 'goods_id');
        $goods_map = [
            ['id',    'in',   $goods_id_arr]
        ];
        $goods_list = OzonGoodsModel::mk()->where($goods_map)->column('id,shop_id', 'id');
        $err_data = $success_data = [];
        foreach ($sku_list as $key => $value) {
            if(empty($value['ozon_sku'])){
                $err_data[] = $value['goods_nu'].'sku同步库存失败,没有ozonsku';
            }
            $shop_id = !empty($goods_list[$value['goods_id']]['shop_id']) ? $goods_list[$value['goods_id']]['shop_id'] : 0;
            if(empty($shop_id)){
                $err_data[] = $value['goods_nu'].'sku店铺信息有误';
            }
            $success_data[$shop_id][] = $value;
        }
        if(!empty($err_data)){
            $this->error(implode('<br>', $err_data));
        }
        if(empty($success_data)){
            $this->error('没有需要同步库存的sku');
        }
        // 获取店铺信息
        $shop_ids = array_keys($success_data);
        $shop_map = [
            ['id',    'in',   $shop_ids]
        ];
        $shop_list = ShopsModel::mk()->where($shop_map)->column('id,client_id,api_key', 'id');
        foreach($success_data as $shop_id => $sku_arr){
            $shop_config = [
                'client_id' => !empty($shop_list[$shop_id]['client_id']) ? $shop_list[$shop_id]['client_id'] : '',
                'api_key' => !empty($shop_list[$shop_id]['api_key']) ? $shop_list[$shop_id]['api_key'] : '',
            ];
            try {
                $ozon_client = new Ozon($shop_config);
            } catch (\Exception $th) {
                $this->error($th->getMessage());
            }
            $ozon_err = [];
            foreach(array_chunk($sku_arr, 100) as $sku_chunk){
                $skus = array_column($sku_chunk, 'ozon_sku');
                $ozon_ret = $ozon_client->getStocksInfo($skus);
                if(empty($ozon_ret['code'])){
                    $ozon_err[] = $ozon_client->getErr();
                }
                $res_data = $ozon_ret['data']['result'];
                if(empty($res_data)){
                    $update_data = ['stock' => 0, 'push_status' => 2];
                    $map = [
                        ['goods_nu',    'in', array_column($sku_chunk, 'goods_nu')],
                        ['goods_id',    'in', array_column($sku_chunk, 'goods_id')]
                    ];
                    OzonGoodsSkuStockModel::mk()->where($map)->update($update_data);
                }else{
                    $product_id_arr = array_column($sku_chunk, null, 'product_id');
                    foreach ($res_data as $key => $value) {
                        $goods_id = !empty($product_id_arr[$value['product_id']]['goods_id']) ? $product_id_arr[$value['product_id']]['goods_id'] : 0;
                        $goods_nu = !empty($product_id_arr[$value['product_id']]['goods_nu']) ? $product_id_arr[$value['product_id']]['goods_nu'] : '';
                        $map = [
                            ['goods_id',        '=', $goods_id],
                            ['goods_nu',        '=', $goods_nu],
                            ['warehouse_id',    '=', $value['warehouse_id']]
                        ];
                        $update_data = ['stock' => $value['present'], 'ozon_stock' => $value['present'], 'ozon_reserved_stock' => $value['reserved'], 'push_status' => 2];
                        OzonGoodsSkuStockModel::mk()->where($map)->update($update_data);
                    }
                }
            }
            if(!empty($ozon_err)){
                $this->error('同步库存失败,错误信息:'.implode('<br>', $ozon_err));
            }
        }
        $this->success('同步库存成功');
    }

    /**
     * 推送库存
     * @auth true
     * @Description
     * @author wangqinghui
     * @date 2024-12-31 16:49
     * @return void
     */
    public function pushStock()
    {
        $sku_ids = $this->request->post('sku_ids', '');
        if(empty($sku_ids)){
            $this->error('请选择需要推送的sku');
        }
        $sku_id_arr = explode(',', $sku_ids);
        if(empty($sku_id_arr)){
            $this->error('请选择需要推送的sku');
        }
        // 获取库存信息
        $map = [
            ['id',      'in',   $sku_id_arr]
        ];
        $filed = 'id,shop_id,goods_id,goods_nu,warehouse_id,stock';
        $sku_stock_data = OzonGoodsSkuStockModel::mk()->field($filed)->where($map)->select()->toArray();
        if(empty($sku_stock_data)){
            $this->error('没有需要推送的sku库存');
        }
        // 获取sku信息
        $map = [
            ['goods_nu',    'in',   array_column($sku_stock_data, 'goods_nu')]
        ];
        $sku_data = OzonGoodsSkuModel::mk()->where($map)->column('id,goods_nu,product_id', 'goods_nu');
        if(empty($sku_data)){
            $this->error('推送的sku信息有误');
        }
        $err_data = $success_data = $sku_stock_ids = [];
        foreach ($sku_stock_data as $key => $value) {
            if(empty($sku_data[$value['goods_nu']]['product_id'])){
                $err_data[] = $value['goods_nu'].'sku库存推送失败,sku未同步到ozon平台';
            }
            $success_data[$value['shop_id']][] = [
                'offer_id'          =>      $value['goods_nu'],
                'product_id'        =>      $sku_data[$value['goods_nu']]['product_id'],
                'stock'             =>      $value['stock'],
                'warehouse_id'      =>      $value['warehouse_id'],
            ];
            $sku_stock_ids[$value['warehouse_id'].$value['goods_nu']] = $value['id'];
        }
        if(!empty($err_data)){
            $this->error(implode('<br>', $err_data));
        }
        if(empty($success_data)){
            $this->error('没有需要推送的sku库存');
        }
        // 获取店铺信息
        $shop_ids = array_keys($success_data);
        $shop_map = [
            ['id',    'in',   $shop_ids]
        ];
        $shop_list = ShopsModel::mk()->where($shop_map)->column('id,client_id,api_key', 'id');
        if(empty($shop_list)){
            $this->error('没有找到对应的店铺');
        }
        foreach ($success_data as $shop_id => $stock_data) {
            $shop_obj = !empty($shop_list[$shop_id]) ? $shop_list[$shop_id] : [];
            // 获得对应的service
            try {
                $ozon_client = new Ozon($shop_obj);
            } catch (\Exception $th) {
                $this->error($th->getMessage());
            }
            $push_ret = OzonGoodsModel::mk()->actPushGoodsStock($ozon_client, $stock_data, $sku_stock_ids);
            if(!empty($push_ret['error'])){
                $this->error('推送失败:'.implode('<br>', $push_ret['error']));
            }
        }
        $this->success('推送成功');
    }
}